package 线程;

public class SynchronizedStatic implements Runnable {
    static boolean flag = true;

    //静态同步方法   同步监视器是类
    public static synchronized void test0() {
        for (int i = 0; i < 2000; i++) {
            System.out.println("test0:" + Thread.currentThread().getName() + " " + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizedStatic ss = new SynchronizedStatic();
        new Thread(ss).start();
        //睡眠1ms，让第一条线程获得执行时机
        Thread.sleep(1);
        new Thread(ss).start();
    }

    //非静态同步方法 同步监视器是this，指调用该方法的java对象
    public synchronized void test1() {
        for (int i = 0; i < 2000; i++) {
            System.out.println("test0:" + Thread.currentThread().getName() + " " + i);
        }
    }

    public void test2() {
        synchronized (this) {//同步代码块需要显示指定同步监视器
            for (int i = 0; i < 2000; i++) {
                System.out.println("test1:" + Thread.currentThread().getName() + " " + i);
            }
        }
    }

    @Override
    public void run() {
        if (flag) {
            flag = false;
            //test0();
            test1();
        } else {
            flag = true;
            test2();
        }
    }
}
